/**
 * 动画数字
 * @author shengzhi
 * 使用方法：
 *   <div v-animated-number="num"></div> // num 为需展示的数字
 */
import formatNumber from 'filters/format-number'

var animatedNumber = (el, binding) => {
  if (binding.value === binding.oldValue) {
    return
  }
  const STEP = 40
  let start = 0
  let end = binding.value
  let digit = end.toString().split('.')[1]

  if (digit) {
    end = end * Math.pow(10, digit.length)
  }

  let stepSize = Math.ceil((end - start) / STEP)

  const format = (num, digit) => {
    let result = num
    if (digit) {
      result = num / Math.pow(10, digit.length)
    }
    return formatNumber(result)
  }

  const loop = () => {
    el.innerHTML = format(start, digit)
    if (Math.abs(start + stepSize) < Math.abs(end)) {
      start = start + stepSize
    } else {
      start = end
      el.innerHTML = format(start, digit)
    }
    if (Math.abs(start) < Math.abs(end)) {
      window.requestAnimationFrame(loop)
    }
  }
  window.requestAnimationFrame(loop)
}

export default animatedNumber
